/**
 * Created by ZFL on 2018/2/1.
 */
/**
 * Created by ZFL on 2017/9/13.
 */

/**
 * Created by ZFL on 2017/9/13.
 */


var inventoryId=0;    //库存id
var specLength=0;     //所有规格的个数
var seledArr=[];   //选中的规格组
var seledIndexArr=[];   //存放选中的规格组位置

var vm=new Vue({
    el:"#goodsEle",
    data:{
        lowestPrice:'',         //最低价格
        suggestedPrice:'',      //建议售价
        specPrice:'',           //规格页价格
        name:'',                //商品名称
        goodsId:'',             //商品id
        shareIcon:'',           //分享图片
        brand:{},               //品牌信息
        commentCount:0,         //评论总数
        commentList:[],         //评论数组
        roleId:0,               //角色ID
        storeName:'',           //店铺名字
        roleMoney:0,            //达人获得钱
        channelShow:false,      //判断是否是海淘商品
        goodDetailList:[],      //商品详情
        specImg:'',              //选中规格之后的图片
        goodsServiceList:[],     //服务条款
        specDescList:[],         //规格数组
        specId:'',               //规格ID
        specDescName :'一',         //默认规格
        backMoney:'' ,            //购买返多少欧币
        userDirectCommission:0,   //获得佣金
        inventoryNum:0,          //商品库存
        storesList:[],           //推荐店铺列表
        isShow:false,           //推荐店铺是否出现
        goodsExplainList:[]    //限购数量

    },
    methods:{
        //设置默认选中规格
        setSpec:function(){
            var _this = this;
            _this.specDescList.forEach(function(value,index){
                value.value.forEach(function(val,ind){
                    _this.$set(val,'seled',false);
                    _this.$set(val,'flag',false);
                })
            });

        },
        //选中规格事件
        selSpecFun:function(ele,item,index,ind){
            var _this = this;
            item.value.forEach(function(value,index){
                value.seled = false;
            });
            ele.seled = true;
            if(ele.specificationDetailImage.length>0){
                _this.specImg=ele.specificationDetailImage;
            }

            _this.specId = '';
            _this.specDescName = '';

            //_this.specDescName += ele.detailName+' ';
            //_this.specId +=ele.specificationDetailId;'

            var obj={};
            obj.index=index;
            obj.specificationDetailId=ele.specificationDetailId;
            obj.detailName=ele.detailName;
            //判断点击是否是同一行   如果同一行 进行替换    不属于同一行   则加入规格组
            if($.inArray(index,seledIndexArr)<0){
                seledArr.push(obj);
                seledIndexArr.push(index);
            }else{
                var num=$.inArray(index,seledIndexArr);
                seledArr[num]=obj;
                seledIndexArr[num]=index;
            }

            //选中一个规格   就要在视图的界面显示
            seledArr.forEach(function(val,ind){
                _this.specDescName += val.detailName+' ';
                _this.specId += val.specificationDetailId;
                if(ind!= _this.specDescList.length-1){
                    _this.specId += ',';
                }
            })



            //每选中一个规格  就要判断下是否需要检查库存(选中的规格个数要和总规格数相等)
            if(seledIndexArr.length==specLength){
                isInvertory(_this.specId)
            }


        }
    },
    filters:{
        unitConFun:function(val){
            return divideNumber(val,100)
        }
    }




})

var seledArr=[];   //选中的规格组
var noInverArr=[];    //没有库存的规格组
var agio = '';    //佣金类型 分享出来的商品
var goodsId =1;  //商品ID
var userId = 0;  //用户ID
var pageNum = 1;
var pageSize = 10;
var loading = false;
var productNum = '';    //商品库存
var productName = '';   //商品规格与分类名字
var goods_obj = {};     //商品信息
var shareUserId = '';   //分享人ID
var userGoodsId= $.getPara('userGoodsId');
function appInit(){
    PageInit();
}
//滚动加载商品评论
//window.onscroll = function(){
//    var scr = $(window).scrollTop();
//    var clientH = document.body.clientHeight;
//    var scrollH = document.body.scrollHeight;
//    if(scr+clientH == scrollH){
//        if(loading) return;
//        loading = true;
//        pageNum++;
//        //YDUI.dialog.loading.open('正在加载...');
//        setTimeout(function(){
//            getGoodsComment();
//        },100)
//    }
//};

function PageInit(){

        if($.getPara('goodsId')){
            goodsId = $.getPara('goodsId');  //商品id
        }
        if($.getPara('userTalentId')){
            shareUserId=$.getPara('userTalentId');    //分享人id
            //talentId=$.getPara('userTalentId');
            com_obj.talentId=$.getPara('userTalentId');
        }

      initApi();   //加载商品详情



}

var userlatitude=0;  //用户所在纬度
var userlongitude=0;  //用户所在经度

var storelatitude=0;  //商家所在纬度
var storelongitude=0;  //商家所在经度


//userlatitude= $.getStorage('userlatitude');
//storelongitude= $.getStorage('storelongitude');



//banner轮播图
function swiperFun(){
    var swiper = new Swiper('.swiper-container', {
        pagination:'.swiper-pagination',
        //loop:true,
        //autoplay:3000,
        paginationClickable: true,
        longSwipesRatio: 0.3,
        touchRatio:1,
        observer:true,//修改swiper自己或子元素时，自动初始化swiper
        observeParents:true,//修改swiper的父元素时，自动初始化swiper


    });
}
//加载普通商品详情   分享期商品详情
function initApi(){
    var obj ={};
    obj.goodsId = goodsId;
    if($.getPara('mallStoreId')){
        obj.storeId=$.getPara('mallStoreId');
    }else{
        if(com_obj.mallStoreId){
            obj.storeId=com_obj.mallStoreId;
        }else{
            obj.storeId= $.getStorage('mallStoreId');
            com_obj.mallStoreId=$.getStorage('mallStoreId');
        }
    }

    if($.getPara('userTalentId')){
        obj.goodsLinkOwnerUserId=$.getPara('userTalentId');
    }else{
        if(com_obj.userTalentId){
            obj.goodsLinkOwnerUserId=com_obj.userTalentId;
        }else{
            obj.goodsLinkOwnerUserId=0;
        }
    }




    if(com_obj.userId && com_obj.userId > 0){
        obj.userId=com_obj.userId
    }

    $.ajaxHandler({
            model: function () {
                console.log(obj)
                return obj;
            },
            visibleTime: 0,
            visible:'show',
            dataType: "json",
            api:'yg_baijiaplatform/goods/getGoodsDetail',
            success: function (result) {
                if(result.code == 10000){
                    var data = result.data;
                    goods_obj.brandId = data.brandId;


                    vm.goodsId=data.goodsId;
                    goodsId=data.goodsId;
                    getGoodsComment();
                    //加载轮播图
                    var html = '';
                    //视频
                    if(data.videos!==null){
                        data.videos.forEach(function(value,index){
                            html='<div class="swiper-slide"><video controls autoplay><source src='+value.videoUrl+'></video></div>';
                            $('.swiper-wrapper').append(html);

                        })
                    }

                    //图片
                    data.goodNavigateList.forEach(function(value,index){
                        html='<div class="swiper-slide"><img src='+value.navigateImage+' alt=""></div>';
                        $('.swiper-wrapper').append(html);
                    })
                    vm.carouselVideos=data.videos;
                    vm.carouselImgs=data.goodNavigateList;
                    swiperFun();    //轮播图
                    vm.goodsServiceList = data.goodsServiceList;//服务条款
                    vm.backMoney = data.scoreRate * divideNumber(data.lowestPrice,100);
                    vm.shareIcon = data.goodNavigateList[0].navigateImage;  //分享到朋友圈和好友的icon
                    //商品详情

                    data.goodDetailList.forEach(function(value,index){
                        vm.goodDetailList.push(value);

                    });
                    vm.lowestPrice = divideNumber(data.lowestPrice,100);
                    vm.specPrice=divideNumber(data.lowestPrice,100);
                    vm.specPrice=divideNumber(data.lowestPrice,100);
                    vm.specImg = data.goodNavigateImage;   //默认规格图片

                    vm.suggestedPrice = divideNumber(data.suggestedPrice,100);
                    if(vm.suggestedPrice <= vm.lowestPrice){
                        $('.original-price').hide();
                    }
                    vm.name = data.name;

                    vm.storeName = data.storeName;

                    vm.brand = data.brand;
                    //getSpec();
                    judgeInventFun();
                    vm.goodsExplainList=data.goodsExplainList;
                    if($.getPara("talentId")!=""){//分享商品只能购买，不能加入购物车
                        $(".add-shop").hide();
                        $(".goods-shop").hide();
                    }
                }else{
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }
        }
    );
}



//判断尺寸与规格
function  judgeInventFun() {
    var obj = {};
    obj.goodsId=goodsId;
    if(com_obj.mallStoreId){
        obj.storeId = com_obj.mallStoreId;
    }else{
        obj.storeId = $.getPara("mallStoreId");
    }
    $.ajaxHandler({
        model:function () {
            return obj;
        },
        visibleTime: 100,
        visible:'show',
        dataType: "json",
        api: 'yg_baijiaplatform/goods/filterSku',
        success:function (result) {
            // 请求成功
            if(result.code == 10000){
                productName = '';
                var data = result.data;
                vm.specDescList=data;
                specLength=data.length;
                vm.setSpec();

                //if(vm.inventDataOne.length == 0){
                //    // 获得第一种规格的数据
                //    obj = {};
                //    obj.name = data[0].name;
                //    obj.specificationId = data[0].specificationId;
                //    obj.value = data[0].value;
                //    obj.value.forEach(function (val,index) {
                //        val.couldNot = 1;
                //    });
                //    vm.inventDataOne.push(obj);
                //}
                //if(vm.inventDataTwo.length ==0&&data[1]){
                //    // 获得第二种规格的数据
                //    obj = {};
                //    obj.name = data[1].name;
                //    obj.specificationId = data[1].specificationId;
                //    obj.value = data[1].value;
                //    obj.value.forEach(function (val,index) {
                //        val.couldNot = 1;
                //    });
                //    vm.inventDataTwo.push(obj);
                //}
                //// 如果第一种规格只有一个则选中
                //
                //if(vm.inventDataOne[0].value.length == 1){
                //    vm.setChecked(1,0,vm.inventDataOne[0].value[0]);
                //}
                //// 存储规格的名字
                //productName = vm.inventDataOne[0].name;
                //// 如果第二种规格只有一种则选中
                //if(data[1]){
                //    if(vm.inventDataTwo[0].value.length == 1){
                //        vm.setChecked(2,0,vm.inventDataTwo[0].value[0]);
                //    }
                //    // 存储规格的名字
                //    productName = vm.inventDataOne[0].name +'与'+vm.inventDataTwo[0].name;
                //}


            }else if(result.code == 20102){
                $.toast('缺少必传参数','text')
            }else if(result.code == 20000){
                $.toast('异常','text');
            }else {
                $.toptip(result.message,"warning");
            }
        }
    });
}
//判断哪些规格没有库存

function isInvertory(specInfo){
    $.ajaxHandler({
            model: function () {
                var obj ={};
                obj.goodId =goodsId;
                obj.specInfo = specInfo;
                if(com_obj.mallStoreId){
                    obj.storeId=com_obj.mallStoreId;
                }else{
                    obj.storeId=$.getPara("mallStoreId");
                }
                return obj;
            },
            visibleTime: 100,
            visible:'hide',
            dataType: "json",
            api: 'yg_baijiaplatform/product/getProductInfoBySpecInfo',
            success: function (result) {
                var data = result.data;
                if (result.code == 10000) {
                    productTotal = data.inventoryNum;
                    vm.inventoryNum=data.inventoryNum;
                    if(productTotal>0){
                        vm.checkedYesNo = true; //立即购买样式修改
                        // $('.add-shop-btn').addClass('active');
                        goods_obj.productId = data.productId;//货品ID
                        goods_obj.inventoryId = data.inventoryId;//库存ID
                        goods_obj.storeId  = data.storeId;//店铺ID
                        goods_obj.productType  = data.produtType;//商品类型
                        goods_obj.inventoryNum = data.inventoryNum; //商品库存
                        vm.isShow=true;    //改变立即购买(加入购物车按钮样式)
                        //vm.salePrice = parseFloat(divideNumber(data.salePrice,100));//商品售价
                    }
                }else if(result.code==20409){
                    YDUI.dialog.toast('无库存啦~~换一个试试',1000)
                }
                else if(result.code == 20000) {
                    $.toast('异常',"text");
                    vm.message = '异常';
                    vm.checkedYesNo = false;  //立即购买样式修改
                    productTotal = 0;
                }else{
                    $.toast(''+result.message+'',"text");
                    vm.message = result.message;
                    vm.checkedYesNo = false;  //立即购买样式修改
                    productTotal = 0;
                }
            }
        }
    );
}


//加入购物车按钮 立即购买
function addShop(type){
    //type=1 加入购物车  type=2立即购买
    //isInvertory();
    $('video').hide();
    goods_obj.type = type;

    //if(com_obj.userId && com_obj.userId>0){
        $('#shop-layer-id').addClass('back-show');
        $('.shop-fixed').addClass('back-show animation-slide-bottom');
        if(type == 1){
            $('.add-shop-btn').text("加入购物车");
        }else if(type ==2){
            $('.add-shop-btn').text("立即购买");
        }
        //isInvertory();
        $('.add-shop-btn').attr('data-type',type);
        $('.html').css({height:"100%"});
        $('.goods').css({height:"100%",overflow:"hidden"});
    //}else{
    //    var httpUrl = window.location.href;
    //    window.location.href = '../user/user_login.html?href='+httpUrl+'';
    //}
}



//商品评论
function getGoodsComment(){
    $.ajaxHandler({
        model: function () {
            var obj = {};
            obj.goodId = goodsId;
            obj.pageNum = pageNum;
            obj.pageSize = pageSize;
            vm.goodsId=goodsId;

            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        visible:'hide',
        api:'yg_baijiaplatform/goodsComment/listGoodsCommentByGoodId',
        success: function (result) {
            if(result.code == 10000){
                var data = result.data;
                vm.commentCount = data.count;  //评论总数
                if(data.list.length > 0){
                    // 加载数据
                    loading = false;
                    data.list.forEach(function(value,index){
                        value.imgArr = [];
                        if(value.image1 != ''){
                            value.imgArr.push(value.image1);
                        }
                        if(value.image2 != ''){
                            value.imgArr.push(value.image2);
                        }
                        if(value.image2 != ''){
                            value.imgArr.push(value.image3);
                        }
                        vm.commentList.push(value);
                    });
                    //表示这是最后一页数据
                    if(data.pageCount == pageNum){
                        loading = true;
                    }
                }else {
                    loading = true;
                }

            }else{
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    });
}

//选择规格后进行购买
function SelectAddShop(){
    var buyNum=parseInt($('input[name="quantity"]').val());
        if(seledArr.length==vm.specDescList.length&&buyNum<=vm.inventoryNum){

            if(goods_obj.type == 1){
                //加入购物车
                submitShop();
            }else if(goods_obj.type == 2){
                //立即购买
                goodsBuy();
            }
        }

}

var mallStoreId=0;
if(com_obj.mallStoreId){
    mallStoreId=com_obj.mallStoreId;
}else{
    mallStoreId= $.getStorage('mallStoreId');
    com_obj.mallStoreId=$.getStorage('mallStoreId');
}

//提交到购物车中
function submitShop(){
    var obj ={};
    obj.goodId = goodsId;//商品ID
    obj.inventoryId  = goods_obj.inventoryId;//库存ID
    obj.mallStoreId=mallStoreId;
    obj.productId  = goods_obj.productId;//货品ID
    obj.productNum = $('input[name="quantity"]').val(); //购买数量
    obj.storeId  = goods_obj.storeId; //门店ID
    if(com_obj.talentId){
        obj.talentId=com_obj.talentId;
    }
    obj.type = goods_obj.productType; //商品类型
    obj.userId =com_obj.userId;
    $.ajaxHandler({
            model: function () {
                return obj;
            },
            visibleTime: 100,
            visible:'show',
            approve:true,
            dataType: "json",
            api: 'yg_baijiaplatform/mallShoppingCart/addShoppingCart',
            success: function (result) {
                if (result.code == 10000) {
                    YDUI.dialog.toast('加入购物车成功', 'success', 1000);
                    clearShop();
                }else if(result.code == 20100){
                    YDUI.dialog.toast('认证失败，重新登录', 'error', 1000);
                }else {
                    YDUI.dialog.toast('异常', 'error', 1000);
                }
            }
        }
    );
}
//立即购买
function goodsBuy(){
    var  para={};
    para.activityType=0;    //活动类型
    para.applywelfareId=0;  //福利社Id
    para.shareActivityId = 0; //分享活动id
    para.mallStoreId=com_obj.mallStoreId;    //微商城门店id
    para.userId=com_obj.userId;
    para.goodsSimpleVoList=[];
    var obj={};
    obj.brandId=goods_obj.brandId;   //品牌Id
    obj.goodId=goodsId;           //商品id
    obj.inventoryId=goods_obj.inventoryId;    //库存ID
    obj.quantity= parseInt($('input[name="quantity"]').val());    //数量
    if(com_obj.talentId){
        obj.talentId=com_obj.talentId;      //分享人Id
    }
    if(com_obj.talentShareGoodId){
        obj.talentShareGoodId=com_obj.talentShareGoodId;   //商品分享id
    }
    obj.type=goods_obj.productType;
    para.goodsSimpleVoList.push(obj);
    para.lat=userlatitude;   //用户纬度
    para.lon=userlongitude;  //用户经度
    para.mallStoreId=com_obj.mallStoreId;   //微商城门吊id
    para.noFilter=1;
    para.userId=com_obj.userId;       //用户id
    $.setStorage('goodObject',para);
    if(!$.getStorage("userOpenid")) {
        //获取Code
        $.GetWXCode();
    }else if($.isWX() &&$.getStorage("userOpenid")){
        window.location.href='../pay/goodsPay.html';
    }



    //}else{
    //    //非微信浏览器中
    //    window.location.href= $.wxApi()+'b2c/pay/goodsPay.html';
    //}





}






//数量绑定
function  ProductCode(type){
    var num = parseInt($('input[name="quantity"]').val());

    if(type==1){
        //++

        if(num>=vm.inventoryNum&&seledArr.length==vm.specDescList.length){
            //$('.shop-buy-number-control .increase i').addClass('active');

            YDUI.dialog.toast('没库存了',1000);
        }else if(seledArr.length!==vm.specDescList.length){
            YDUI.dialog.toast('请选择商品规格',1000);

        }else{
            $('input[name="quantity"]').val(num+1);
            $('.shop-buy-number-control .decrease i').removeClass('active');
        }

    }else if(type==0){
        //--
        if(num !="" && num > 1){
            $('input[name="quantity"]').val(num-1);
        }
        if($('input[name="quantity"]').val() == 1){
            $('.shop-buy-number-control .decrease i').addClass('active');
        }
    }
}




//加入购物车layer关闭
function clearShop(){
    $('#shop-layer-id').removeClass('back-show');
    $('.shop-fixed').removeClass('back-show animation-slide-bottom');
    $('html').css({height:"auto"});
    $('.goods').removeAttr("style");
    $('video').show();
}
//打开服务条约
function deliverPact(){
    $('#server-layer-id').addClass('back-show');
    $('.server-fixed').addClass('back-show animation-slide-bottom');
    $(".goods-foot").slideUp();
    $('.html').css({height:"100%"});
    $('.goods').css({height:"100%",overflow:"hidden"});
}
//关闭服务条款
function cloasePact() {
    $('#server-layer-id').removeClass('back-show');
    $('.server-fixed').removeClass('back-show animation-slide-bottom');
    $(".goods-foot").slideDown();
    $('html').css({height:"100%"});
    $('.goods').css({height:"100%",overflow:"auto"});
}



//显示灰色 jQuery 遮罩层
function showBg() {
    var bh = $("body").height();
    var bw = $("body").width();
    $("#fullbg").css({
        height:bh,
        width:bw,
        display:"block",
    });
    $("#dialog").show()
    $('body').css("overflow","hidden")
    ;

}
//关闭灰色 jQuery 遮罩
function closeBg(){
    $("#fullbg,#dialog").hide();
    $('body').css("overflow","visible")
}



//进入购物车页面
function goShopPage(){
    window.location.href = '../shop/index.html';
}





